package DAO;

import Base.Tema;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 *
 * @author Rosana
 */
public class DaoTema {
    
    public int inserirTema(Tema tema)
    {
        Connection con = FactoryConnection.getConnection();
        ResultSet rs;
        int cod = -1;
        
        if(tema.getId() ==-1)
        {
            String query = "INSERT INTO tema(descricao) VALUES(?) returning id";

            try
            {
                CallableStatement stmt = con.prepareCall(query);
                stmt.setString(1, tema.getDescricao());
                
                rs = stmt.executeQuery();
                
                if(rs.next())
                {
                    cod = rs.getInt("id");
                    System.out.println("código retornado: "+cod);
                }
                stmt.close();                  
            }
            catch (SQLException e)
            {
                System.out.println("Erro no SQL do inserir pergunta");
                e.printStackTrace();
                return cod;
            }
        }
        return cod;
    }
    
    
    public int verificarTema(String tema)
    {
        Connection con = FactoryConnection.getConnection();
        ResultSet rs;
          
        String query = "Select * from tema where descricao = ?";
        int retorno = -1;
       
        try
        {
            CallableStatement stmt = con.prepareCall(query);
            stmt.setString(1, tema);

            rs = stmt.executeQuery();

            if(rs.next())
            {
                retorno = rs.getInt("id");                
            }
            stmt.close();                  
        }
        catch (SQLException e)
        {
            System.out.println("Erro no SQL do consultar tema");
            e.printStackTrace();
            retorno = -1;
        }
        
        return retorno;   
    }
    
    public ArrayList<Tema> listaTemas()
    {
        Connection con = FactoryConnection.getConnection();
        ResultSet rs;
          
        String query = "Select * from tema";
        
        ArrayList<Tema> lista = new ArrayList();
       
        try
        {
            PreparedStatement stmt = con.prepareCall(query);
            
            rs = stmt.executeQuery();

            if(rs.next())
            {
                do
                {
                    lista.add(new Tema(rs.getInt("id"), rs.getString("descricao")));
                }while(rs.next());
            }
            stmt.close();                  
        }
        catch (SQLException e)
        {
            System.out.println("Erro no SQL do lista de temas");
            e.printStackTrace();
            return null;
        }
        
        return lista;
    }
}
